package com.wn.class30.weixinmessageHandler;

import com.alibaba.fastjson.JSON;
import com.wn.class30.service.TokenService;
import org.springframework.stereotype.Component;
import org.weixin4j.loader.ITokenLoader;
import org.weixin4j.model.base.Token;
import javax.annotation.Resource;
import java.util.Date;

@Component
public class MyTokenLoadler implements ITokenLoader {

    @Resource
    private TokenService tokenService;
    @Override
    public Token get() {
        com.wn.class30.entity.Token token = null;
        try {
            token = tokenService.queryById(1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(token!= null && token.getAccessToken()!=null && token.getAccessToken()!="" && token.getExpirationTime()!=null && (new Date()).getTime()<token.getExpirationTime()){
            return JSON.parseObject(token.getAccessToken(),Token.class);
        }
        return null;
    }

    @Override
    public void refresh(Token token) {
        String accessToken = JSON.toJSONString(token);
        long  expirationTime =token.getExpires_in()*1000+token.getCreate_time()-600000L;
        com.wn.class30.entity.Token token1 = new com.wn.class30.entity.Token();
        token1.setId(1);
        token1.setAccessToken(accessToken);
        token1.setExpirationTime(expirationTime);
        try {
            com.wn.class30.entity.Token token2 = tokenService.queryById(1);
            if(token2==null){
                tokenService.insertToken(token1);
            }else{
            tokenService.updateById(token1);}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
